package com.example.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;
import com.example.gulimall.product.config.MyThreadPoolConfig;
import com.example.gulimall.product.dao.SkuInfoDao;
import com.example.gulimall.product.entity.SkuImagesEntity;
import com.example.gulimall.product.entity.SkuInfoEntity;
import com.example.gulimall.product.entity.SpuInfoDescEntity;
import com.example.gulimall.product.service.*;
import com.example.gulimall.product.vo.SkuItemSaleAttrVo;
import com.example.gulimall.product.vo.SkuItemVo;
import com.example.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService imagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired // 引入已经放入容器了，所以可以直接自动注入
    ThreadPoolExecutor executor;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        //由于第一次进入页面没有传这几个参数，因此直接params.get()获取会空引用
        if (params.containsKey("key")||params.containsKey("catelogId")||params.containsKey("brandId")||params.containsKey("min")||params.containsKey("max")){

            String key = (String) params.get("key");
            if(!StringUtils.isEmpty(key)){
                queryWrapper.and((wrapper)->{
                    wrapper.eq("sku_id",key).or().like("sku_name",key);
                });
            }
            String catelogId = (String) params.get("catelogId");
            if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){

                queryWrapper.eq("catalog_id",catelogId);
            }

            String brandId = (String) params.get("brandId");
            if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(catelogId)){
                queryWrapper.eq("brand_id",brandId);
            }

            String min = (String) params.get("min");
            if(!StringUtils.isEmpty(min)){
                //大于等于
                queryWrapper.ge("price",min);
            }

            String max = (String) params.get("max");
            if(!StringUtils.isEmpty(max)  ){
                try{
                    BigDecimal bigDecimal = new BigDecimal(max);

                    if(bigDecimal.compareTo(new BigDecimal("0"))==1){

                        queryWrapper.le("price",max);
                    }
                }catch (Exception e){

                }

            }

        }




        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品详情异步编排执行
     * 345 必须等待1  做完才能做，2 都没有关系，
     * 345 彼此又没关系，所以可以在开三个线程
     * 因此可以异步编排为1做完在345线程，345为三个线程
     * 2 都没有关系也可以开一个信息线程
     * @param skuId
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo=new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1 sku 基本信息获取，pms_sku_inf->o
            SkuInfoEntity info = baseMapper.selectById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3 获取spu销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4 获取spu的介绍 pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);
        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5 获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2 sku图片信息 pms_sku_images
            List<SkuImagesEntity> imagesEntities = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntities);
        }, executor);
        //等待所有任务都完成
         CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture).get();

        return  skuItemVo;
    }


}